package web.login.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import web.login.bo.LoginBo;
import web.login.entity.Login;
import web.login.to.LoginTo;


@Controller
@RequestMapping("/login.htm")
public class LoginController {

	private final Log log = LogFactory.getLog(LoginController.class);
	
	@Autowired
	private LoginBo loginBo;
	
	public LoginBo getLoginBo() {
		return loginBo;
	}
	
	public void setLoginBo(LoginBo loginBo) {
		this.loginBo = loginBo;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView onLoad(HttpServletRequest request) 
	{
		LoginTo loginTo = new LoginTo();
		
		log.info("INSIDE LOGIN CONTROLLER'S onLoad METHOD ::: ");
		ModelAndView mav = new ModelAndView("login");
		mav.addObject("loginTo",loginTo);
		return mav;
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView onSubmit(@ModelAttribute("loginTo")LoginTo loginTo) {
		
		
		System.out.println("Inside onSubmit ...");
		boolean credentialsMatched = false;
		List<Login> logins = loginBo.getAllUsers();
		
		for(Login login:logins)
		{
			if(loginTo.getUserName().equalsIgnoreCase(login.getUsername()))
				credentialsMatched = true;
		}
		
		if(!credentialsMatched)
			return new ModelAndView("login");
		else
			return new ModelAndView("welcome");
	}
}
